import React, { memo, useEffect, useCallback, useState } from 'react';
import { Modal, Form, Select, DatePicker, TimePicker, InputNumber, Input, Button, Space, message, Alert } from 'antd';
import { CalendarOutlined, ClockCircleOutlined, EnvironmentOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { IScheduleTemplateFormProps } from '@/types/components/schedule';
import type { IScheduleTemplateCreateRequest, IScheduleTemplateUpdateRequest } from '@/types/schedule';
import { DayOfWeekEnum, ScheduleTemplateStatusEnum } from '@/types/schedule';
import { validateScheduleTemplateData } from '@/utils/validation';
import styles from './ScheduleTemplateForm.module.css';

const { Option } = Select;
const { TextArea } = Input;

/**
 * 课程模板表单组件
 * @description 用于创建和编辑课程安排模板的表单组件
 */
const ScheduleTemplateForm: React.FC<IScheduleTemplateFormProps> = memo(({
  template,
  students,
  courses,
  visible,
  mode,
  onSubmit,
  onCancel,
  loading = false,
  presetDate,
  presetTime
}) => {
  const [form] = Form.useForm();
  const [conflicts, setConflicts] = useState<string[]>([]);

  // 星期选项
  const dayOfWeekOptions = [
    { value: DayOfWeekEnum.MONDAY, label: '星期一' },
    { value: DayOfWeekEnum.TUESDAY, label: '星期二' },
    { value: DayOfWeekEnum.WEDNESDAY, label: '星期三' },
    { value: DayOfWeekEnum.THURSDAY, label: '星期四' },
    { value: DayOfWeekEnum.FRIDAY, label: '星期五' },
    { value: DayOfWeekEnum.SATURDAY, label: '星期六' },
    { value: DayOfWeekEnum.SUNDAY, label: '星期日' }
  ];

  // 表单初始化
  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && template) {
        // 编辑模式，填充现有数据
        form.setFieldsValue({
          studentId: template.studentId,
          courseId: template.courseId,
          startDate: dayjs(template.startDate),
          startTime: dayjs(`2000-01-01 ${template.startTime}`),
          endTime: dayjs(`2000-01-01 ${template.endTime}`),
          dayOfWeek: template.dayOfWeek,
          totalCount: template.totalCount,
          location: template.location,
          remark: template.remark,
          status: template.status
        });
      } else {
        // 创建模式，重置表单
        form.resetFields();
        const defaultValues: any = {
          totalCount: 10,
          status: ScheduleTemplateStatusEnum.ACTIVE
        };

        // 应用预设值
        if (presetDate) {
          defaultValues.startDate = dayjs(presetDate);
          defaultValues.dayOfWeek = dayjs(presetDate).day() || 7; // 转换为1-7格式
        }
        
        if (presetTime) {
          const [startTime, endTime] = presetTime.split('-');
          if (startTime) {
            defaultValues.startTime = dayjs(`2000-01-01 ${startTime}`);
          }
          if (endTime) {
            defaultValues.endTime = dayjs(`2000-01-01 ${endTime}`);
          }
        }

        form.setFieldsValue(defaultValues);
      }
    }
  }, [visible, mode, template, form, presetDate, presetTime]);

  // 处理表单提交
  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      
      // 构造提交数据
      const submitData = mode === 'edit' && template ? {
        id: template.id,
        studentId: values.studentId,
        courseId: values.courseId,
        startDate: values.startDate.format('YYYY-MM-DD'),
        startTime: values.startTime.format('HH:mm'),
        endTime: values.endTime.format('HH:mm'),
        dayOfWeek: values.dayOfWeek,
        totalCount: values.totalCount,
        location: values.location?.trim() || undefined,
        remark: values.remark?.trim() || undefined,
        status: values.status
      } as IScheduleTemplateUpdateRequest : {
        studentId: values.studentId,
        courseId: values.courseId,
        startDate: values.startDate.format('YYYY-MM-DD'),
        startTime: values.startTime.format('HH:mm'),
        endTime: values.endTime.format('HH:mm'),
        dayOfWeek: values.dayOfWeek,
        totalCount: values.totalCount,
        location: values.location?.trim() || undefined,
        remark: values.remark?.trim() || undefined,
        status: values.status
      } as IScheduleTemplateCreateRequest;

      // 数据验证
      const validationResult = mode === 'create' 
        ? validateScheduleTemplateData(submitData as IScheduleTemplateCreateRequest)
        : { isValid: true, message: '' };
      if (!validationResult.isValid) {
        message.error(validationResult.message);
        return;
      }

      await onSubmit(submitData);
      form.resetFields();
      setConflicts([]);
    } catch (error) {
      console.error('表单提交失败:', error);
      if (error instanceof Error) {
        message.error(error.message);
      }
    }
  }, [form, onSubmit]);

  // 处理取消操作
  const handleCancel = useCallback(() => {
    form.resetFields();
    setConflicts([]);
    onCancel();
  }, [form, onCancel]);

  // 处理开始日期变化，自动设置星期几
  const handleStartDateChange = useCallback((date: dayjs.Dayjs | null) => {
    if (date) {
      const dayOfWeek = date.day() || 7; // 转换为1-7格式
      form.setFieldValue('dayOfWeek', dayOfWeek);
    }
  }, [form]);

  // 验证时间范围
  const validateTimeRange = useCallback(async () => {
    const startTime = form.getFieldValue('startTime');
    const endTime = form.getFieldValue('endTime');
    
    if (startTime && endTime) {
      if (endTime.isBefore(startTime) || endTime.isSame(startTime)) {
        throw new Error('结束时间必须晚于开始时间');
      }
    }
  }, [form]);

  // 渲染学生选项
  const renderStudentOptions = () => {
    return students.map(student => (
      <Option key={student.id} value={student.id}>
        <div className={styles.studentOption}>
          <span className={styles.studentName}>{student.name}</span>
          <span className={styles.studentId}>({student.studentId})</span>
        </div>
      </Option>
    ));
  };

  // 渲染课程选项
  const renderCourseOptions = () => {
    return courses.map(course => (
      <Option key={course.id} value={course.id}>
        <div className={styles.courseOption}>
          <div 
            className={styles.courseColor}
            style={{ backgroundColor: course.color }}
          />
          <span className={styles.courseName}>{course.name}</span>
          <span className={styles.courseTeacher}>- {course.teacher}</span>
        </div>
      </Option>
    ));
  };

  return (
    <Modal
      title={
        <div className={styles.modalTitle}>
          <CalendarOutlined className={styles.titleIcon} />
          {mode === 'create' ? '添加课程安排' : '编辑课程安排'}
        </div>
      }
      open={visible}
      onCancel={handleCancel}
      footer={
        <Space>
          <Button onClick={handleCancel}>
            取消
          </Button>
          <Button
            type="primary"
            loading={loading}
            onClick={handleSubmit}
          >
            {mode === 'create' ? '添加' : '保存'}
          </Button>
        </Space>
      }
      width={600}
      destroyOnHidden
      className={styles.templateFormModal}
    >
      {conflicts.length > 0 && (
        <Alert
          message="时间冲突警告"
          description={
            <ul>
              {conflicts.map((conflict, index) => (
                <li key={index}>{conflict}</li>
              ))}
            </ul>
          }
          type="warning"
          showIcon
          className={styles.conflictAlert}
        />
      )}

      <Form
        form={form}
        layout="vertical"
        className={styles.templateForm}
        autoComplete="off"
      >
        <div className={styles.formRow}>
          <Form.Item
            name="studentId"
            label="学生"
            rules={[{ required: true, message: '请选择学生' }]}
            className={styles.halfWidth}
          >
            <Select
              placeholder="请选择学生"
              showSearch
              filterOption={(input, option) => {
                const student = students.find(s => s.id === option?.value);
                return student ? 
                  student.name.toLowerCase().includes(input.toLowerCase()) ||
                  student.studentId.toLowerCase().includes(input.toLowerCase())
                  : false;
              }}
            >
              {renderStudentOptions()}
            </Select>
          </Form.Item>

          <Form.Item
            name="courseId"
            label="课程"
            rules={[{ required: true, message: '请选择课程' }]}
            className={styles.halfWidth}
          >
            <Select
              placeholder="请选择课程"
              showSearch
              filterOption={(input, option) => {
                const course = courses.find(c => c.id === option?.value);
                return course ? 
                  course.name.toLowerCase().includes(input.toLowerCase()) ||
                  course.teacher.toLowerCase().includes(input.toLowerCase())
                  : false;
              }}
            >
              {renderCourseOptions()}
            </Select>
          </Form.Item>
        </div>

        <div className={styles.formRow}>
          <Form.Item
            name="startDate"
            label="开始日期"
            rules={[{ required: true, message: '请选择开始日期' }]}
            className={styles.halfWidth}
          >
            <DatePicker
              placeholder="请选择开始日期"
              format="YYYY-MM-DD"
              onChange={handleStartDateChange}
              className={styles.fullWidth}
            />
          </Form.Item>

          <Form.Item
            name="dayOfWeek"
            label="星期几"
            rules={[{ required: true, message: '请选择星期几' }]}
            className={styles.halfWidth}
          >
            <Select placeholder="请选择星期几">
              {dayOfWeekOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </div>

        <div className={styles.formRow}>
          <Form.Item
            name="startTime"
            label="开始时间"
            rules={[
              { required: true, message: '请选择开始时间' },
              { validator: validateTimeRange }
            ]}
            className={styles.thirdWidth}
          >
            <TimePicker
              placeholder="开始时间"
              format="HH:mm"
              minuteStep={15}
              className={styles.fullWidth}
            />
          </Form.Item>

          <Form.Item
            name="endTime"
            label="结束时间"
            rules={[
              { required: true, message: '请选择结束时间' },
              { validator: validateTimeRange }
            ]}
            className={styles.thirdWidth}
          >
            <TimePicker
              placeholder="结束时间"
              format="HH:mm"
              minuteStep={15}
              className={styles.fullWidth}
            />
          </Form.Item>

          <Form.Item
            name="totalCount"
            label="总次数"
            rules={[
              { required: true, message: '请输入总次数' },
              { type: 'number', min: 1, max: 1000, message: '总次数必须在1-1000之间' }
            ]}
            className={styles.thirdWidth}
          >
            <InputNumber
              placeholder="总次数"
              min={1}
              max={1000}
              className={styles.fullWidth}
            />
          </Form.Item>
        </div>

        <Form.Item
          name="location"
          label="上课地点"
        >
          <Input
            prefix={<EnvironmentOutlined />}
            placeholder="请输入上课地点"
            maxLength={100}
          />
        </Form.Item>

        <Form.Item
          name="remark"
          label="备注"
        >
          <TextArea
            placeholder="请输入备注信息"
            rows={3}
            maxLength={200}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
});

ScheduleTemplateForm.displayName = 'ScheduleTemplateForm';

export default ScheduleTemplateForm;